<template>
  <!-- auto-upload 选择好图片后立刻自动上传后端还是手动点击某按钮上传后端  这里选择了 false，所以 action 也不会触发，这里进行手动文件上传请求-->
  <el-upload
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="handleUpload"
  >
    <img
      v-if="props.avatar"
      :src="uploadAvatarUrl"
      class="avatar"
    />
    <el-icon
      v-else
      class="avatar-uploader-icon"
    >
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script setup>
import { Plus } from '@element-plus/icons-vue'
import { computed } from 'vue'
const props = defineProps({
  avatar: String
})
const emit = defineEmits(['handle'])
// 每次选择完图片之后的回调，file是文件信息，file.raw是原生文件对象
const handleUpload = (file) => {
  emit('handle', file.raw)
}
const uploadAvatarUrl = computed(() => {
  return props.avatar.includes('blob') ? props.avatar : 'http://localhost:3000' + props.avatar
})
</script>

<style scoped lang="scss">
// 由于 scoped 属性，局部作用域，所以需要通过 ::v-deep 操作符来深层设置嵌套样式
::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep .el-upload:hover {
  border-color: var(--el-color-primary);
}

::v-deep .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}
</style>